package com.milkTeaServer.controller;

import com.milkTeaServer.bean.Cart;
import com.milkTeaServer.bean.Order;
import com.milkTeaServer.bean.User;
import com.milkTeaServer.dao.CartDao;
import com.milkTeaServer.dao.OrderDao;
import com.milkTeaServer.dao.UserDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/cart")
public class CartController {
    @Autowired
    CartDao dao;

    @Autowired
    OrderDao orderDao;

    @RequestMapping("/add")
    @ResponseBody
    public Map addOrderToCart(@RequestBody Cart cart) {
        Map map = new HashMap();
        Cart cart1 = dao.saveAndFlush(cart);
        if (cart1 != null) {
            map.put("success", true);
            map.put("massage", "添加订单至购物车成功!");
            map.put("data", cart1);
        } else {
            map.put("success", false);
            map.put("massage", "添加订单至购物车失败!");
            map.put("data", null);
        }
        return map;
    }

    @RequestMapping("/findByUserId")
    @ResponseBody
    public Map getCartListByUserId(@RequestBody User user) {
        Map map = new HashMap();
        System.out.println(user.getId());
        List<Cart> cartById = dao.findCartById(user.getId());
        if (cartById != null) {
            map.put("success", true);
            map.put("massage", "获取购物车成功!");
            map.put("data", cartById);
        } else {
            map.put("success", false);
            map.put("massage", "获取购物车失败!");
            map.put("data", null);
        }
        return map;
    }

    @RequestMapping("/delete")
    @ResponseBody
    public Map deleteCart(@RequestBody Cart cart) {
        Map map = new HashMap();
        dao.deleteById(cart.getId());
        List<Order> orderById = orderDao.findOrderById(cart.getOrderid());
        orderDao.deleteById(orderById.get(0).getId());
        map.put("success", true);
        map.put("massage", "成功!");
        return map;
    }
}
